
#include "connect_thread.h"
#include <string>
#include <QtCore/QStringList>
#include <QtGui/QSound>

//#include <QtCore/QObject>
commp_thread::commp_thread(QString comm_name,TTYSettings inp_settings,QObject * parent)
://UNUSED is_connection_opened(false)
 is_reading(false)
,is_writing(false)
,is_timer_inited(false)
,read_interval(inp_settings.read_interval)
{
	memcpy(&this_thread_settings,&inp_settings,sizeof(inp_settings));
	stored_data_waiting_endl.clear();
	this->comm_name=comm_name;
	//recieve simple string, 13 10 end
	simple_or_xbee=true;
	memcpy(&(this->winSerialConnector.main_settings),&inp_settings,sizeof(inp_settings));
	endlsymbol=QString("")+QChar(char(13))+QChar(char(10));
}
commp_thread::commp_thread(QString comm_name,TTYSettings inp_settings,QString endlsymbol,QObject * parent)
: is_reading(false)
,is_writing(false)
,is_timer_inited(false)
,read_interval(inp_settings.read_interval)
{
	memcpy(&this_thread_settings,&inp_settings,sizeof(inp_settings));
	stored_data_waiting_endl.clear();
	this->comm_name=comm_name;
	//recieve simple string, 13 10 end
	simple_or_xbee=true;
	memcpy(&(this->winSerialConnector.main_settings),&inp_settings,sizeof(inp_settings));
	//call simple constructor
	//;
	this->endlsymbol=endlsymbol;
}
void commp_thread::ForceTimer()
{
	
	if(!this->ConnectToSerial())
	{
		QSound::play("fail.wav");
		qDebug("commp_thread::run(): can't open com port");
		emit(FailToConnect());
		//close thread??
		this->~commp_thread();
		return;

	}
	CommTimer = new QTimer(this);
	is_timer_inited=true;
	CommTimer->start(read_interval);
	qDebug("commp_thread::run(): Starting");
	QObject::connect(CommTimer, SIGNAL(timeout()), this,
			SLOT(OnTimerHit()));
	//emit IsConnected();

}
void commp_thread::OnTimerHit()
{
	qDebug("commp_thread::OnTimerHit(): hit the timer!");
	//we read with the blocks of 512 char, if lesser, resize tmprd till message size
	std::vector<unsigned char> tmprd(512);
	if(winSerialConnector.Read(tmprd))
	{
		if(simple_or_xbee) //we are in simple mode
		{
			std::string tmpstr2;
			tmpstr2.resize(tmprd.size());
			tmpstr2.assign(tmprd.begin(),tmprd.end());
			qDebug(tmpstr2.c_str());
			//000 protection
			if(tmpstr2.size()>=3)
			{
				QString tmpstr3("");
				tmpstr3.append(tmpstr2.substr(0,3).c_str());
				if(tmpstr3.contains("000"))
				{

					
					qDebug ("000 string detected, ignore it.");
					return;
				}
				if(tmpstr3.contains("I'm"))
				{


					qDebug ("alive string detected, ignore it.");
					return;
				}
			}

			stored_data_waiting_endl.append(tmpstr2.c_str());
			int sepstrlen;

			//QString dd=QString("")+QChar(char(13))+QChar(char(10));
			sepstrlen=endlsymbol.size();
			//#13#10??
			bool is_any_endl_found =stored_data_waiting_endl.contains(endlsymbol);
			if(is_any_endl_found)
			{
				QStringList tmplist(stored_data_waiting_endl.split(endlsymbol,QString::SkipEmptyParts));
				if(tmplist.size()>0)
				{
					//send all catched substrings
					for(int i=0;i<tmplist.size()-1;i++)
					{

						emit StringCatched(tmplist[i]);			//QString(tmpstr2.c_str()));

					}
					//last substring is ended with endl
					if(stored_data_waiting_endl.size()-sepstrlen >0 &&
					   stored_data_waiting_endl[stored_data_waiting_endl.size()-sepstrlen]==endlsymbol[0])

					{
						//send last ste
						emit StringCatched(tmplist[tmplist.size()-1]);
						stored_data_waiting_endl.clear();
					}
					else
					{
						//store last part of substring for later use
						stored_data_waiting_endl.clear();
						stored_data_waiting_endl.append(tmplist[tmplist.size()-1]);

					}
				}
			}
		}
		else //read as xbee input
		{

			QString	tmpstr2;//tmpstr.resize(0);
			for(size_t i=0;i<tmprd.size();i++)
			tmpstr2.push_back(QChar(tmprd[i]));
			if(tmpstr2.size()>4)
			emit StringCatched(tmpstr2);

		}
	}
}
void commp_thread::SendQStr(QString str_in)
{
	std::vector<unsigned char> msg1(str_in.size());
	std::string tmpstdstr(str_in.toAscii().constData());
	msg1.assign(tmpstdstr.begin(),tmpstdstr.end());
	int size1= str_in.size();
	std::vector<unsigned char> msg2(0);
	for(int i=0;i<size1;i++)
	{
		msg2.push_back(str_in[i].toAscii());

	}
	winSerialConnector.Write(msg2);
}
void commp_thread::SendQStr1(vector_of_uchars str_in)
{
	int fff=0;
	//winSerialConnector.Write(str_in);
}
bool commp_thread::ConnectToSerial()
{
	
	return winSerialConnector.Connect(std::string(comm_name.toAscii().constData()),this_thread_settings.baudrate);//115200);;
}
void commp_thread::SetConnectionMode(int new_mode)
{
	//TODO checks for connections, ets

	if(new_mode==0)
		simple_or_xbee=true;
	else if(new_mode==2)
		simple_or_xbee=false;
}

commp_thread::~commp_thread()
{
	
	if(is_timer_inited)
	{
		CommTimer->stop();
		delete CommTimer;
	}
	qDebug("commp_thread::~commp_thread(): Destructor Called");

}

void commp_thread::Selfdestruct()
{
	//double usage! timerisinitedifonly isconnected!
	if(is_timer_inited)
	winSerialConnector.Disconnect();
	
	this->~commp_thread();
}

